* Creates 2009 onwards master data
use "$savedata/ami_analysis_mainspef.dta", clear

keep if finyear>2008

* Merge in the various connected sets

foreach x in 10 25 50 100{
cap drop _merge
merge m:1 trust_code using "$savedata/connect_total`x'_09onwards.dta", keepusing(akm_set)
drop _merge
}

foreach x in 10 25 50 100{
	replace akm_set_mainspef`x'=0 if akm_set_mainspef`x'==.
}

su *set*

gen one = 1

* Create hospital-doctor indicators (interact hosp and doctor id)
egen hdid = group(doctor_id trust_num)
egen  hyid = group(trust_num finyear)
egen doctime = group(doctor_id finyear)

* Create survival variables
foreach x in 7 30 90 365{
gen survive`x' = 1
replace survive`x' = 0 if all_death`x'==1 
}

forval x=1(1)20{
encode fulldiag3_`x', gen(di`x')
replace di`x'=0 if di`x'==.
}

* Make sure I have timing variables
cap drop admidate_month 
cap drop admidate_day 
cap drop admidate_year
cap drop dow

gen admidate_month = month(ami_date)
gen admidate_day = day(ami_date)
gen admidate_year = year(ami_date)

* Create day of the week
gen dow = dow(mdy(admidate_month, admidate_day, admidate_year))

* Generate A&e arrival variable
gen d_amb = aearrivalmode
replace d_amb = 9 if d_amb==.

merge m:1 pconsult finyear using "$savedata/cardio_experience0317.dta"
drop if _merge==2

gen nonami3 = total3 - ami3
egen std_ami3 = std(ami3)
egen std_nonami3 = std(nonami3)

gen shock = 0
gen arrest = 0
gen arythmia = 0
gen arthero = 0

forval x=1(1)20{
	replace shock = 1 if substr(fulldiag3_`x',1,3)=="R57"
	replace arrest = 1 if substr(fulldiag3_`x',1,3)=="I46"
	replace arythmia = 1 if substr(fulldiag3_`x',1,3)=="I49"
	replace arthero = 1 if substr(fulldiag3_`x',1,4)=="I251"
}

cap drop stemi

gen stemi2 = 0

foreach x in I210 I211 I212 I213 I220 I221{
replace stemi2=1 if fulldiag3_1=="`x'"
}

save "$savedata/masterdata_09onwards.dta", replace

